package ai.handlers;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.eclipse.e4.core.di.annotations.CanExecute;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;

import ai.utils.DateUtils;

public class SaveHandler {

	@CanExecute
	public boolean canExecute(EPartService partService) {
		return true;
	}

	@Execute
	public void execute(EPartService partService, Shell shell) {
		FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
		fileDialog.setText("请选择文件保存路径");
		fileDialog.setFilterExtensions(new String[] { "*.txt" });
		fileDialog.setFileName("回答记录" + DateUtils.getNowStr2() + ".txt");
		String filePath = fileDialog.open();
		if (filePath != null && filePath.length() > 0) {
			try {
				FileWriter writer = new FileWriter(filePath, StandardCharsets.UTF_8);
				MPart part = partService.findPart("ai.part.sample");
				writer.write(part.getContext().get(StyledText.class).getText());
				writer.close(); // 记得关闭文件
				System.out.println("内容已写入文件。");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}